<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link th:href="@{/img/vc_icon.png}" rel="shortcut icon"/>
    <link th:href="@{/font/iconfont.css}" rel="stylesheet"/>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet"/>
    <link th:href="@{/select2/select_gj.css}" rel="stylesheet"/>
    <link th:href="@{/select2/select2-bootstrap.min.css}" rel="stylesheet"/>
    <link th:href="@{/css/ry-ui.css}" rel="stylesheet"/>
    <title>Dialog recording chat </title>
</head>
<style>
    /***
        Dialog start
     */
    .cell-foot a {
        color: inherit;
        text-decoration: none;
    }

    .floating-button {
        position: fixed;
        bottom: 5%;
        right: 1.5%;
        background-color: #00A65A;
        color: #fff;
        border-radius: 50%;
        width: 45px;
        height: 45px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 24px;
        cursor: pointer;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    }

    /** 聊天窗口样式   */
    .dialog {
        position: fixed;
        bottom: 80px;
        right: 20px;
        background-color: #fff;
        color: #333;
        border-radius: 5px;
        width: 350px;
        padding: 20px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
        display: none;
    }

    .low-amplitude {
        background-color: green;
    }

    .medium-amplitude {
        background-color: yellow;
    }

    .high-amplitude {
        background-color: red;
    }
</style>
<body>
<div class="floating-button" onclick="toggleDialog()"><i class="iconfont icon-chat"></i></div>
<div class="row">
    <div class="dialog" id="dialog">
        <div class="select-list">
            <ul>
                <li>
                    <button type="button" class="btn btn-sm btn-block startRecording" id="startRecording">
                        <i class="iconfont icon-mic-on"></i>
                    </button>
                </li>
                <li>
                    <select class="form-control" id="selectOption" >
                        <option value="51000" selected>51000</option>
                        <option value="51001">51001</option>
                        <option value="51002">51002</option>
                    </select>
                </li>
                <li>
                    <button type="button" class="btn btn-sm btn-success ">
                        <i class="iconfont icon-fasong"></i>
                    </button>
                </li>
            </ul>
        </div>
        <div style="margin-top: 3px">
            <textarea id="result" rows="5" cols="50" class="form-control"
                      readonly></textarea>
            <input type="file" id="audioFile" style="display: none;">
        </div>
    </div>
</div>
</body>
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/font/iconfont.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>

<script th:src="@{/select2/select_gj.min.js}"></script>
<script>
    // let ROOT = [[${#servletContext.contextPath}]];
    let url = "ws://" + window.location.host + "/websocket/amplitude";
    let ws;//websocket实例
    let lockReconnect = false;//避免重复连接
    let startRecordingButton;

    //切换Chat窗口状态
    function toggleDialog() {
        let dialog = document.getElementById("dialog");
        dialog.style.display = (dialog.style.display === "none") ? 'block' : 'none';
    }

    // 关闭对话框
    function closeDialog() {
        let dialog = document.getElementById("dialog");
        dialog.style.display = "none";
    }

    $(function (){
        createWebSocket(url)
        myEvents()
        getAmplitude();
        // 获取录音按钮元素
        startRecordingButton = document.getElementById('startRecording');
        document.getElementById("dialog").style.display = "none";
    })

    function myEvents(){
        //开始、停止录音
        $('.select-list').on('click', '.startRecording', function (e) {
            let $this = $(e.target);
            if ($this.hasClass("icon-mic-on")){
                $this.removeClass("icon-mic-on");
                $this.addClass("icon-mic-off");
                startRecording();
            } else {
                $this.removeClass("icon-mic-off");
                $this.addClass("icon-mic-on");
                stopRecording();
            }
        })
    }

    // 开始录音
    function startRecording() {
        document.getElementById('result').value = "";
        $.ajax({
            url: '/startRecording',
            type: 'POST',
            success: function (data) {
                console.log(data)
            },
            error: function (xhr, status, error) {
                console.error(error)
            }
        })
    }

    // 停止录音
    function stopRecording() {
        let fileInput = document.getElementById('audioFile');
        let file = fileInput.files[0];

        let formData = new FormData();
        formData.append('file', file)

        $.ajax({
            url: '/stopRecording',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                console.log(JSON.stringify(data))
                document.getElementById('result').value = data
            },
            error: function (xhr, status, error) {
                console.log(JSON.stringify(error))
                console.error(error)
            }
        })
    }

    function createWebSocket(url) {
        try {
            if ('WebSocket' in window){
                ws = new WebSocket(url);
            }else if ('MozWebSocket' in window){
                ws = new WebSocket(url);
            }else {
                console.warn("something was wrong")
            }
            initEventHandler(url);
        }catch (e){
            reconnect(url)
        }
    }
    function initEventHandler(url){
        ws.onopen = function (event) {
            heartCheck.reset().start();
        }
        ws.onclose = function (event) {
            reconnect(url)
        }
        ws.onerror = function (event) {
            reconnect(url)
        }
        ws.onmessage = function (event) {
            heartCheck.reset().start();
            if (event.data === "null"){
                return
            }
            initEventHandlerMessage(event);
        }
    }
    function initEventHandlerMessage(event){
        const {data} = event;
        let {amplitude} = JQuery.parse(data);
        if (amplitude){
            let result = document.getElementById('result');
            result.value = amplitude;
        }
    }
    const heartCheck = {
        timeout: 60000,//60秒
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
                //这里发送一个心跳，后端收到后，返回一个心跳消息，isTrusted
                //onmessage拿到返回的心跳就说明连接正常
                var json = {"HeartBeat": new Date().getTime()};
                ws.send(JSON.stringify(json));
                self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置，说明后端主动断开了
                    ws.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                }, self.timeout)
            }, this.timeout)
        }
    }
    //重连
    function reconnect(url) {
        if (lockReconnect) return;
        lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function () {
            createWebSocket(url);
            lockReconnect = false;
        }, 2000);
    }

    // 定义获取音频振幅的函数
    function getAmplitude() {
        // 在这里获取音频振幅的值
        // 例如，可以使用Web Audio API来获取振幅

        // 假设获取到的振幅值存储在变量 amplitude 中
        // 假设振幅范围为 0 到 1 之间
        const amplitude = 0.5;

        // 根据振幅值更新按钮样式
        updateButtonStyle(amplitude);

        // 使用定时器或 requestAnimationFrame 来定期获取振幅值
        requestAnimationFrame(getAmplitude);
    }

    // 定义更新按钮样式的函数
    function updateButtonStyle(volume) {
        if (volume < 0.3) {
            if (startRecordingButton.hasClass( 'medium-amplitude', 'high-amplitude')){
                startRecordingButton.removeClass('medium-amplitude', 'high-amplitude');
            }
            startRecordingButton.addClass('low-amplitude');
        } else if (volume < 0.7) {
            if (startRecordingButton.hasClass('low-amplitude', 'high-amplitude')) {
                startRecordingButton.removeClass('low-amplitude', 'high-amplitude');
            }
            startRecordingButton.addClass('medium-amplitude');
        } else {
            if (startRecordingButton.hasClass('low-amplitude', 'medium-amplitude')) {
                startRecordingButton.removeClass('low-amplitude', 'medium-amplitude');
            }
            startRecordingButton.addClass('high-amplitude');
        }
    }
</script>
</html>